package com.jdk.learn.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

/**
 * 信号量
 */
public class MultiThreadSemaphore extends Thread{
    private Semaphore semaphore;
    public MultiThreadSemaphore(Semaphore semaphore) {
        this.semaphore=semaphore;
    }

    @Override
    public void run() {
        try {
            int count = semaphore.availablePermits();//可用数量
            if (count > 0) {
                System.out.println(getName() + "可以使用，还有：" + count + "个");
            } else {
                System.out.println(getName() + "不能使用");
            }
            semaphore.acquire();
            System.out.println(getName()+"使用中。。。。");
            Thread.sleep(300);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            semaphore.release();
            System.out.println(getName()+"使用完毕");
        }
    }

    public static void main(String[] args) {

        Semaphore semaphore=new Semaphore(3);
        for (int i = 0; i < 5; i++) {
            new MultiThreadSemaphore(semaphore).start();
        }
    }
}
